from sqlalchemy import Column, Integer, String, Boolean, DateTime, Text
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from app.core.database import Base

class Permission(Base):
    """权限模型"""
    __tablename__ = "permissions"
    
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), unique=True, index=True, nullable=False, comment="权限名称")
    display_name = Column(String(100), nullable=False, comment="显示名称")
    description = Column(Text, nullable=True, comment="权限描述")
    module = Column(String(50), nullable=False, comment="所属模块")
    action = Column(String(50), nullable=False, comment="操作类型")
    resource = Column(String(100), nullable=True, comment="资源标识")
    
    # 状态字段
    is_active = Column(Boolean, default=True, comment="是否激活")
    is_system = Column(Boolean, default=False, comment="是否系统权限")
    
    # 时间字段
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="创建时间")
    updated_at = Column(DateTime(timezone=True), onupdate=func.now(), comment="更新时间")
    
    # 关系
    roles = relationship("Role", secondary="role_permissions", back_populates="permissions")
    
    def __repr__(self):
        return f"<Permission(id={self.id}, name='{self.name}', module='{self.module}')>"
    
    @classmethod
    def create_permission_name(cls, module: str, action: str, resource: str = None) -> str:
        """生成权限名称"""
        if resource:
            return f"{module}:{action}:{resource}"
        return f"{module}:{action}"